import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smart_devices/icons/src/antd_icons.dart';
import 'package:smart_devices/routes/index.dart';
import 'package:smart_devices/ui/draw_under_line.dart';
import 'package:smart_devices/ui/my_custom_paint_line.dart';
import 'package:smart_devices/utils/colors.dart';
import 'package:smart_devices/utils/styles.dart';
import 'package:smart_devices/utils/tools.dart';

import 'info_logic.dart';

typedef SliverHeaderBuilder = Widget Function(
    BuildContext context, double shrinkOffset, bool overlapsContent);

class RepairInfoView extends StatefulWidget {
  const RepairInfoView({Key? key}) : super(key: key);

  @override
  State<RepairInfoView> createState() => _RepairInfoView();
}

class _RepairInfoView extends State<RepairInfoView> {
  final controller = Get.find<RepairInfoLogic>();

  late ScrollController scrollController;

  List<GlobalKey> bodyKeyList = [];

  List<double> cardOffsetList = [];

  GlobalKey globalKey = GlobalKey();

  List<String> tabs = ['故障信息', '维修处理', '工作量', '执行进度', '更换备件', '验证信息'];

  /// 滑动组件在屏幕的位置
  double listDy = 0;

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
    cardOffsetList = List.filled(tabs.length, -1.0);
    fillKeyList();
    useWidgetsBinding().addPostFrameCallback((da) {
      fillOffset();
      scrollController.addListener(() {
        updateOffset();
        var currentIndex = createIndex(scrollController.offset);
        if (currentIndex != controller.tabIndex.value &&
            !controller.isTabClick.value) {
          controller.tabIndex.value = currentIndex;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
            size: 15,
          ),
          onPressed: Get.back,
        ),
        automaticallyImplyLeading: false,
        title: Text(
          '工单详情',
          style: StylesUtils.customTextStyle(
              fontSize: 18, fontWeight: FontWeight.w700),
        ),
        centerTitle: true,
      ),
      body: Obx(() => CustomScrollView(
            key: globalKey,
            controller: scrollController,
            slivers: [
              SliverPersistentHeader(
                  // 不固定顶部
                  pinned: false,
                  delegate: SliverHeaderDelegate(
                      maxHeight: 220,
                      minHeight: 220,
                      child: DrawUnderLine(
                        child: Container(
                          decoration: const BoxDecoration(color: Colors.white),
                          margin: const EdgeInsets.only(bottom: 10),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Container(
                                    width: 140,
                                    height: 140,
                                    alignment: Alignment.center,
                                    child: Container(
                                      width: 120,
                                      height: 120,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(5),
                                        color:
                                            ColorsUtils.parseColorFromHexString(
                                                ColorsUtils.color669e),
                                      ),
                                      child: ToolsUtils.assetImageSvg(
                                          'u4201.svg',
                                          width: 46,
                                          height: 58),
                                    ),
                                  ),
                                  Expanded(
                                      child: Container(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 10),
                                    child: Column(
                                      children: [
                                        Container(
                                          height: 40,
                                          alignment: Alignment.centerLeft,
                                          child: Text(
                                            controller.details.value.name,
                                            style: StylesUtils.customTextStyle(
                                                fontSize: 18,
                                                fontWeight: FontWeight.w700,
                                                color: ColorsUtils.color1c24),
                                          ),
                                        ),
                                        Container(
                                          height: 30,
                                          alignment: Alignment.centerLeft,
                                          child: Wrap(
                                            spacing: 5,
                                            children: [
                                              Text(
                                                '设备编号：',
                                                style:
                                                    StylesUtils.customTextStyle(
                                                        color: ColorsUtils
                                                            .color3333),
                                              ),
                                              Text(
                                                controller.details.value.code,
                                                style:
                                                    StylesUtils.customTextStyle(
                                                        color: ColorsUtils
                                                            .colorAaaa),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          height: 30,
                                          alignment: Alignment.centerLeft,
                                          child: Wrap(
                                            spacing: 5,
                                            children: [
                                              Text(
                                                '规格型号：',
                                                style:
                                                    StylesUtils.customTextStyle(
                                                        color: ColorsUtils
                                                            .color3333),
                                              ),
                                              Text(
                                                controller.details.value.model,
                                                style:
                                                    StylesUtils.customTextStyle(
                                                        color: ColorsUtils
                                                            .colorAaaa),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          height: 30,
                                          alignment: Alignment.centerLeft,
                                          child: Wrap(
                                            spacing: 5,
                                            children: [
                                              Text(
                                                '设备类型：',
                                                style:
                                                    StylesUtils.customTextStyle(
                                                        color: ColorsUtils
                                                            .color3333),
                                              ),
                                              Text(
                                                controller.details.value.code,
                                                style:
                                                    StylesUtils.customTextStyle(
                                                        color: ColorsUtils
                                                            .colorAaaa),
                                              )
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                  ))
                                ],
                              ),
                              Container(
                                height: 30,
                                padding: const EdgeInsets.only(left: 20),
                                alignment: Alignment.centerLeft,
                                child: Wrap(
                                  spacing: 5,
                                  children: [
                                    Text(
                                      '使用部门：',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color3333),
                                    ),
                                    Text(
                                      '生产部门',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.colorAaaa),
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                height: 30,
                                padding: const EdgeInsets.only(left: 20),
                                alignment: Alignment.centerLeft,
                                child: Wrap(
                                  spacing: 5,
                                  children: [
                                    Text(
                                      '存放位置：',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color3333),
                                    ),
                                    Text(
                                      '新产品N205生产车间二层一车间',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.colorAaaa),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ))),
              SliverPersistentHeader(
                // 固定
                pinned: true,
                delegate: _HeaderDelegate(
                    height: 50,
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      children: appendTabs(),
                    )),
              ),
              SliverList.list(children: getChildrenData()),
            ],
          )),
    );
  }

  @override
  void didUpdateWidget(RepairInfoView oldWidget) {
    super.didUpdateWidget(oldWidget);
    cardOffsetList = List.filled(tabs.length, -1.0);
    useWidgetsBinding().addPostFrameCallback((da) {
      fillOffset();
    });
  }

  List<Widget> appendTabs() {
    return tabs
        .asMap()
        .map((index, value) => MapEntry(
            index,
            Obx(() => InkWell(
                  onTap: () {
                    controller.tabIndex.value = index;
                    controller.isTabClick.value = true;
                    if (index == tabs.length - 1) {
                      scrollController
                          .animateTo(scrollController.position.maxScrollExtent,
                              duration: const Duration(milliseconds: 100),
                              curve: Curves.linear)
                          .whenComplete(() {
                        controller.isTabClick.value = false;
                      });
                      return;
                    }
                    scrollController
                        .animateTo(cardOffsetList[index],
                            duration: const Duration(milliseconds: 100),
                            curve: Curves.linear)
                        .whenComplete(() {
                      controller.isTabClick.value = false;
                    });
                  },
                  child: Container(
                    constraints:
                        const BoxConstraints.expand(width: 76, height: 30),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(
                            controller.tabIndex.value == index ? 15 : 0),
                        color: controller.tabIndex.value == index
                            ? ColorsUtils.parseColorFromHexString(
                                ColorsUtils.color0052)
                            : Colors.transparent),
                    child: Text(
                      value,
                      style: StylesUtils.customTextStyle(
                          color: controller.tabIndex.value == index
                              ? ColorsUtils.colorFfff
                              : ColorsUtils.color0052),
                    ),
                  ),
                ))))
        .values
        .toList();
  }

  List<Widget> getChildrenData() {
    return tabs
        .asMap()
        .map((index, e) => MapEntry(
            index,
            Container(
              key: bodyKeyList[index],
              margin: const EdgeInsets.only(top: 10),
              color: Colors.white,
              child: ListBody(
                children: [
                  SizedBox(
                    height: 40,
                    child: CustomPaint(
                        painter: MyCustomPaintLine(),
                        child: Container(
                          margin: const EdgeInsets.only(left: 30),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            e,
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color6666),
                          ),
                        )),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '是否更换',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '是',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '领用单号',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              'LY2022645',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '领用主题',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '备件领用申请202224',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '申请时间',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '2023-10-17',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '领用原因',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '失灵',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '仓库名称',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '仓库一',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 30),
                          child: Text(
                            '申请备件',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(left: 10),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '3种备件，总数量6',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            Get.toNamed(Routes.deviceSpareParticulars);
                          },
                          child: Container(
                            width: 50,
                            alignment: Alignment.center,
                            child: Icon(
                              AntdIcons.right,
                              color: ColorsUtils.parseColorFromHexString(
                                  ColorsUtils.color9999),
                              size: 15,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )))
        .values
        .toList();
  }

  void fillKeyList() {
    for (int i = 0; i < tabs.length; i++) {
      bodyKeyList.add(GlobalKey());
    }
  }

  void fillOffset() {
    Offset globalToLocal =
        (globalKey.currentContext!.findRenderObject() as RenderBox)
            .localToGlobal(Offset.zero);
    listDy = globalToLocal.dy;
    for (int i = 0, n = tabs.length; i < n; i++) {
      if (cardOffsetList[i] == -1.0 && bodyKeyList[i].currentContext != null) {
        double cardOffset =
            (bodyKeyList[i].currentContext!.findRenderObject() as RenderBox)
                .localToGlobal(Offset.zero) //相对于原点 控件的位置
                .dy; //y点坐标
        cardOffsetList[i] = cardOffset + scrollController.offset - listDy;
      }
    }
  }

  void updateOffset() {
    for (int i = 0, n = tabs.length; i < n; i++) {
      if (bodyKeyList[i].currentContext != null) {
        double cardOffset =
            (bodyKeyList[i].currentContext!.findRenderObject() as RenderBox)
                .localToGlobal(Offset.zero) //相对于原点 控件的位置
                .dy; //y点坐标
        cardOffsetList[i] = cardOffset + scrollController.offset - listDy;
      }
    }
  }

  int createIndex(double offset) {
    int index = 0;
    for (int i = 1; i < tabs.length - 1; i++) {
      if (offset >= cardOffsetList[i] && (offset <= cardOffsetList[i + 1])) {
        return i;
      }
    }
    return index;
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
    Get.delete<RepairInfoLogic>();
  }

  useWidgetsBinding() {
    return WidgetsBinding.instance;
  }
}

class SliverHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double maxHeight;
  final double minHeight;
  final SliverHeaderBuilder builder;

  SliverHeaderDelegate(
      {required this.maxHeight, this.minHeight = 0, required Widget child})
      : builder = ((a, b, c) => child),
        assert(minHeight <= maxHeight && minHeight >= 0);

  //最大和最小高度相同
  SliverHeaderDelegate.fixedHeight({
    required double height,
    required Widget child,
  })  : builder = ((a, b, c) => child),
        maxHeight = height,
        minHeight = height;

  //需要自定义builder时使用
  SliverHeaderDelegate.builder({
    required this.maxHeight,
    this.minHeight = 0,
    required this.builder,
  });

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return builder(context, shrinkOffset, overlapsContent);
  }

  @override
  double get maxExtent => maxHeight;

  @override
  double get minExtent => minHeight;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return oldDelegate.maxExtent != maxExtent ||
        oldDelegate.minExtent != minExtent;
  }
}

class _HeaderDelegate extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;

  const _HeaderDelegate({required this.child, required this.height});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF6f6),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                top: BorderSide(
                    color: ColorsUtils.parseColorFromHexString(
                        ColorsUtils.colorE9e9)),
                bottom: BorderSide(
                    color: ColorsUtils.parseColorFromHexString(
                        ColorsUtils.colorE9e9)))),
        child: child,
      ),
    );
  }

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return this != oldDelegate;
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;
}
